package com.guli.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.guli.gulimall.order.config.AlipayTemplate;
import com.guli.gulimall.order.service.OrderService;
import com.guli.gulimall.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * server {
 * listen       80;
 * server_name gulimall.com  *.gulimall.com c37z155164.wicp.vip;
 * <p>
 * #charset koi8-r;
 * #access_log  /var/log/nginx/log/host.access.log  main;
 * <p>
 * location /static {
 * root   /usr/share/nginx/html;
 * }
 * location /payed/ {
 * proxy_pass http://gulimall;
 * proxy_set_header Host order.gulimall.com;
 * }
 * <p>
 * location / {
 * proxy_pass http://gulimall;
 * proxy_set_header Host $host;
 * }
 * <p>
 * nginx 配置好内网穿透才能成功
 */
@RestController
public class OrderPayedListener {


    @Autowired
    private OrderService orderService;

    @Autowired
    AlipayTemplate alipayTemplate;


    /**
     * 支付宝支付回调
     *
     * @param payAsyncVo
     * @param request
     * @return
     */
    @PostMapping("/payed/notify")
    public String handleAlipayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        // 只要我们收到了支付宝告诉我们支付成功。返回success,支付宝就再也不通知了。
        // 否则25 小时以内完成 8 次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h）。
//        Map<String, String[]> map = request.getParameterMap();
//        for (String key: map.keySet()) {
//            String value = request.getParameter(key);
//            System.out.println("参数名：" + key + "==>参数值：" + value);
//        }
        //验签
//获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
        if (signVerified) {
            System.out.println("签名验证成功");
            //签名验证成功
            String result = orderService.handlePayResult(payAsyncVo);
            return result;
        }else{
            System.out.println("签名验证失败");
            return "error";
        }
    }

}
